package com.briup.service.impl;

import com.briup.bean.ShopCar;

import com.briup.dao.ShopCarMapper;
import com.briup.service.IShopCarService;
import com.briup.util.MyBatisSqlSessionFactory;
import oracle.security.crypto.core.Padding;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class ShopCarServiceIml implements IShopCarService {
    SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
    ShopCarMapper mapper = sqlSession.getMapper(ShopCarMapper.class);

    @Override
    public void saveShopCar(ShopCar sc) {
        //先要判断 我现在加入购物车的这本书 在购物车表里面有没有
        //根据用户id和书籍id来查询数据库当中，该用户有没有添加过这本书的记录
        ShopCar shopCar = mapper.queryShopCarByCidAndBId(sc.getCustomerId(), sc.getBookId());
        if (shopCar != null) {
            //如果有的话，更新num
            //旧的数量+新的数量
            int sum = shopCar.getNum() + sc.getNum();
            shopCar.setNum(sum);
            mapper.updateShopCar(shopCar);
        } else {
            //如果没有的话，直接添加一条新记录
            mapper.saveShopCar(sc);
        }
        sqlSession.commit();
    }

    //更新购物车信息
    @Override
    public void updateShopCar(ShopCar sc) {
        mapper.updateShopCar(sc);
        sqlSession.commit();
    }

    //根据书籍ID和顾客ID查找购物车信息
    @Override
    public ShopCar queryShopCarByCidAndBId(int cid, int bid) {
        return null;
    }

    //根据用户ID查找购物车信息
    @Override
    public List<ShopCar> findShopCarsByCustomer(Integer id) {
        return mapper.findShopCarsByCustomer(id);
    }


    //根据用户id和书籍id来删除购物车信息
    @Override
    public void deleteShopCarByCidAndBId(int cid, int bid) {
        mapper.deleteShopCarByCidAndBId(cid, bid);
        sqlSession.commit();
    }

    //根据用户id来删除购物车信息
    @Override
    public void deleteShopCarByCustomerId(int cid) {
        mapper.deleteShopCarByCustomerId(cid);
        sqlSession.commit();
    }
}
